package recorder

import (
	"sync"
	"time"
)

type SegmentChecker func() bool

type Segment struct {
	mu        sync.Mutex
	id        string
	scene     string
	source    string
	tlvFile   string
	audio     bool
	video     bool
	startTime time.Time
	stopTime  time.Time
	checker   SegmentChecker
}

func NewSegment(currentTime time.Time, scene string, source string, tlvRelPath string, audio bool, video bool, checker SegmentChecker) *Segment {
	segment := &Segment{
		scene:     scene,
		source:    source,
		tlvFile:   tlvRelPath,
		audio:     audio,
		video:     video,
		startTime: currentTime,
		stopTime:  time.Time{},
		checker:   checker,
	}
	log.Infof("new segment the currenttime is:%s:%s", currentTime, source)

	return segment
}

func (s *Segment) Close() {
	s.mu.Lock()
	s.stopTime = time.Now()
	s.mu.Unlock()
}

func (s *Segment) IsLive() bool {
	s.mu.Lock()
	live := s.stopTime.IsZero()
	if live && !s.checker() {
		log.Tracef("scene '%s' source '%s' segment '%s' dead", s.scene, s.source, s.id)
		live = false
	}
	if live {
		log.Tracef("scene '%s' source '%s' segment '%s' live", s.scene, s.source, s.id)
	} else {
		log.Tracef("scene '%s' source '%s' segment '%s' dead", s.scene, s.source, s.id)
	}

	s.mu.Unlock()
	return live
}

func (s *Segment) ToJob() *JobSegment {
	s.mu.Lock()
	if s.stopTime.IsZero() {
		s.stopTime = time.Now()
	}
	js := &JobSegment{
		Rtc:   s.tlvFile,
		Audio: s.audio,
		Video: s.video,
		From:  s.startTime.Unix() * 1000,
		To:    s.stopTime.Unix() * 1000,
	}
	s.mu.Unlock()
	return js
}
